'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import GlassCard from '@/components/ui/GlassCard';
import GlassInput from '@/components/ui/GlassInput';
import PasswordInput from '@/components/ui/PasswordInput';
import GlassButton from '@/components/ui/GlassButton';
import { LogIn } from 'lucide-react';
import api from '@/lib/api';
import toast from 'react-hot-toast';

export default function RegisterPage() {
  const [username, setUsername] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const router = useRouter();

  const handleRegister = async (e: React.FormEvent) => {
    e.preventDefault();
    
    // 表单验证
    if (!username || !password) {
      toast.error('请填写用户名和密码');
      return;
    }
    
    if (username.length < 3) {
      toast.error('用户名至少3个字符');
      return;
    }
    
    if (password.length < 6) {
      toast.error('密码至少6个字符');
      return;
    }
    
    if (password !== confirmPassword) {
      toast.error('两次密码输入不一致');
      return;
    }
    
    setLoading(true);
    
    try {
      // 1. 注册
      await api.post('/auth/register', {
        username,
        email: email || null,
        password
      });
      
      toast.success('注册成功！正在登录...');
      
      // 2. 自动登录
      const formData = new FormData();
      formData.append('username', username);
      formData.append('password', password);
      
      const loginResponse = await api.post('/auth/login', formData, {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
      });
      
      // 3. 保存token
      const { access_token } = loginResponse.data;
      localStorage.setItem('access_token', access_token);
      
      // 4. 获取用户信息
      const { authApi } = await import('@/lib/api');
      const userInfo = await authApi.getCurrentUser();
      
      // 5. 保存到store (同时设置token和用户信息)
      const { useAuthStore } = await import('@/store/authStore');
      useAuthStore.getState().setToken(access_token);
      useAuthStore.getState().setUser(userInfo);
      
      toast.success('登录成功！');
      
      // 6. 跳转到dashboard
      router.push('/dashboard');
    } catch (error: any) {
      console.error('Registration failed:', error);
      const errorMsg = error.response?.data?.detail || error.message || '注册失败';
      toast.error(errorMsg);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center p-4">
      {/* 背景装饰 */}
      <div className="fixed inset-0 -z-10 overflow-hidden">
        <div className="absolute top-1/4 left-1/4 w-96 h-96 bg-indigo-500/30 rounded-full filter blur-3xl animate-blob"></div>
        <div className="absolute top-1/3 right-1/4 w-96 h-96 bg-purple-500/30 rounded-full filter blur-3xl animate-blob animation-delay-2000"></div>
        <div className="absolute bottom-1/4 left-1/3 w-96 h-96 bg-pink-500/30 rounded-full filter blur-3xl animate-blob animation-delay-4000"></div>
      </div>

      <GlassCard className="w-full max-w-md p-8">
        {/* Logo 和标题 */}
        <div className="text-center mb-8">
          <div className="inline-flex items-center justify-center w-16 h-16 mb-4 rounded-2xl bg-gradient-to-br from-indigo-500 to-purple-600 shadow-lg">
            <LogIn className="h-8 w-8 text-white" />
          </div>
          <h1 className="text-3xl font-extrabold mb-2">
            <span className="bg-gradient-to-r from-indigo-600 via-purple-600 to-pink-600 bg-clip-text text-transparent dark:from-indigo-300 dark:via-purple-300 dark:to-pink-300">
              思和智库
            </span>
          </h1>
          <p className="text-base font-semibold bg-gradient-to-r from-indigo-500 to-purple-500 bg-clip-text text-transparent dark:from-indigo-400 dark:to-purple-400">
            创建新账号
          </p>
        </div>

        {/* 注册表单 */}
        <form onSubmit={handleRegister} className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-white/80 mb-2">
              用户名 <span className="text-red-500">*</span>
            </label>
            <GlassInput
              type="text"
              placeholder="请输入用户名（至少3个字符）"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              required
              minLength={3}
              maxLength={50}
              disabled={loading}
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-white/80 mb-2">
              邮箱（可选）
            </label>
            <GlassInput
              type="text"
              placeholder="请输入邮箱（可选）"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              disabled={loading}
            />
            <p className="text-xs text-gray-500 dark:text-white/50 mt-1">
              可以留空，也可以填写邮箱地址
            </p>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-white/80 mb-2">
              密码 <span className="text-red-500">*</span>
            </label>
            <PasswordInput
              placeholder="请输入密码（至少6个字符）"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              required
              minLength={6}
              maxLength={50}
              disabled={loading}
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-white/80 mb-2">
              确认密码 <span className="text-red-500">*</span>
            </label>
            <PasswordInput
              placeholder="请再次输入密码"
              value={confirmPassword}
              onChange={(e) => setConfirmPassword(e.target.value)}
              required
              minLength={6}
              maxLength={50}
              disabled={loading}
            />
          </div>

          <GlassButton
            type="submit"
            variant="primary"
            className="w-full"
            disabled={loading}
          >
            {loading ? '注册中...' : '注册'}
          </GlassButton>
        </form>

        {/* 已有账号？去登录 */}
        <div className="mt-6 text-center">
          <p className="text-sm text-gray-600 dark:text-white/70">
            已有账号？{' '}
            <Link
              href="/login"
              className="text-indigo-500 hover:text-indigo-600 dark:text-indigo-400 dark:hover:text-indigo-300 font-medium transition-colors"
            >
              立即登录
            </Link>
          </p>
        </div>

        {/* Slogan */}
        <div className="mt-8 text-center">
          <p className="text-sm text-gray-500 dark:text-white/50">
            汇聚智慧，赋能政企
          </p>
        </div>
      </GlassCard>
    </div>
  );
}

